package com.gohi.main.wxapi.action;


import java.io.IOException;

import java.util.Date;
import java.util.List;

import com.gohi.main.user.hbm.WxFensi;
import com.gohi.main.user.service.IWxFensiService;
import com.gohi.main.util.EmojiFilter;
import com.gohi.main.util.StringUtil;
import com.gohi.main.util.Utils;


import javax.servlet.ServletContext;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;


import org.apache.log4j.Logger;


import com.gohi.core.web.action.BaseAction;
import com.gohi.main.wxapi.process.*;


import com.gohi.main.wxapi.util.AccoutUtil;
import com.gohi.main.wxapi.vo.*;
import com.gohi.main.wxapi.*;
import com.gohi.main.wxapi.process.*;
import com.gohi.main.wxapi.service.IwxApiProcess;



public class WxpiAction extends BaseAction {
	Logger logger = Logger.getLogger(WxpiAction.class);

	private WxAccount acc;
	private String id;//唯一的区分用户ID
	//微信粉丝
	private IWxFensiService wxFensiService;
	private WxFensi fs;
	
	private IwxApiProcess wxApiProcess; 
	
	public String ck(){
		String openid =null;
		Cookie[] cookie = this.getRequest().getCookies();
		if (cookie != null) {
			for (Cookie ck : cookie) {
				if (ck.getName().equals("openid")) {
					openid = ck.getValue();
				}
			}
		}
		if(openid!=null){
			System.err.println(openid);
			return null;
		}else{
			System.err.println("没有获取到openid");
			return "GETCOOKIE";
		}
			
	}
  public String index() throws IOException{

		HttpServletRequest request = this.getRequest();//
		String code=this.getRequest().getParameter("code");
		if(id!=null && code!=null && !code.equals("")){
			//开始请求 表示授权成功
			WxAccount ac =AccoutUtil.getAccount();//获取当前访问的 appi
			String urls = WxApi.getFenCode(ac.getAppid(), ac.getAppsecret(),code);
			JSONObject jsonObject = WxApi.httpsRequest(urls, "GET", null);
			//获取openid完毕 开始获取详细信息
			//System.err.println(jsonObject.toString());
		   //System.err.println(jsonObject.getString("access_token"));
			if(jsonObject.containsKey("access_token")==false){
				logger.error("微信参数错误");
				return null;
			}
			urls=WxApi.getFenWeb(jsonObject.getString("access_token"), jsonObject.getString("openid"));
			jsonObject=WxApi.httpsRequest(urls, "GET", null);
			//System.err.println("获取到:"+jsonObject.toString());
			id=jsonObject.getString("openid");
			WxFensi fs =	wxFensiService.getById(id);//跑到数据库里查询 一次 判断他是不是已经关注
			if(fs==null){
				WxFensi f =new WxFensi();
				f.setId(jsonObject.get("openid").toString());
				f.setCity(jsonObject.get("city").toString());
				f.setHeadimgurl(jsonObject.get("headimgurl").toString());
				//f.setNickname(EmojiFilter.filterEmoji(jsonObject.get("nickname").toString()));
				f.setNickname(" ");
				f.setLanguage(jsonObject.get("language").toString());
				f.setProvince(jsonObject.get("province").toString());
				f.setSex(Integer.parseInt(jsonObject.get("sex").toString()));
				f.setOpenid(jsonObject.get("openid").toString());
				f.setStatus(1);//
				f.setParid(ac.getParid());
				f.setCreateTime(new Date());
				f.setCountry(jsonObject.get("country").toString());
				wxFensiService.saveOrUpdate(f);	//插入一条数据
				//System.err.println("成功插入一条授权粉丝，未关注："+f.getNickname());
			}
			//cookie保存openid
			String head=jsonObject.getString("headimgurl");
			this.getRequest().setAttribute("img",head);
			Cookie cookie = new Cookie("openid",id);
			cookie.setMaxAge(8888888);
		    this.getResponse().addCookie(cookie);
		}
		
	//	System.err.println(id);
		return "test";
  }
	
/*	public String account() throws Exception {
	HttpServletRequest request = this.getRequest();//
    acc=AccoutUtil.getAccount(getRequest(), id); //去静态方法里面获取
	if(acc==null){
		acc=wxAccountService.getById(id);
		initAccout(acc);//第一次更新 去初始化一次
	}
		String signature = request.getParameter("signature");// 微信加密签名
		String timestamp = request.getParameter("timestamp");// 时间戳
		String echostr = request.getParameter("echostr");// 随机字符串
		//===========================
		if(echostr!=null ){
		//	System.out.println("开始绑定微信号！");
			if (acc != null) {
				//System.out.println(" actTmp.token = " + acc.getToken());
				String tocken = acc.getToken();// 获取token，进行验证；
				String nonce = request.getParameter("nonce");// 随机数
				// 校验成功返回 echostr，成功成为开发者；否则返回error，接入失败
				if (com.gohi.main.wxapi.util.SignUtil.validSign(signature, tocken,
						timestamp, nonce)) {
					//验证成功开始加入刷新的列表
					//System.err.println(id);
					this.getResponse().getWriter().print(echostr);
				}
			}
			this.getResponse().getWriter().print("error");
		
		}else{
			//调用处理
		String text =wxApiProcess.processMsg(this.getRequest(), acc.getAppid(), acc.getAppsecret());
		this.getResponse().getWriter().print(text);
	
	}
		
		return null;
	}*/

	//初始化一个ID
	protected void initAccout(WxAccount wx){
		ServletContext context =this.getSession().getServletContext();
		List<WxAccount> list = (List<WxAccount>) context.getAttribute("account");
		for(WxAccount w : list){
			//遍历获取
			if(!Utils.show(w.getAppid()).equals("")&& w.getAppid().length()>5){
				//判断不等于空的时候 再获取
				if(w.getId().equals(wx.getId())){
					//刷新指定的ID
					Token t  = com.gohi.main.wxapi.process.WxApi.getToken(w.getAppid(),w.getAppsecret());
					//设置
					w.setAccess_token(t.getAccessToken());
					w.setToken_time(t.getExpiresIn()+"");
					w.setLasttime(StringUtil.getTimeSimple());
					logger.info("刷新单个公众号完毕！");
				}
			
			}
		}
		context.setAttribute("account", list);//重新成功
	}

	

	public WxAccount getAcc() {
		return acc;
	}
	public void setAcc(WxAccount acc) {
		this.acc = acc;
	}
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}



	public IWxFensiService getWxFensiService() {
		return wxFensiService;
	}
	public void setWxFensiService(IWxFensiService wxFensiService) {
		this.wxFensiService = wxFensiService;
	}
	public WxFensi getFs() {
		return fs;
	}
	public void setFs(WxFensi fs) {
		this.fs = fs;
	}
	public IwxApiProcess getWxApiProcess() {
		return wxApiProcess;
	}
	public void setWxApiProcess(IwxApiProcess wxApiProcess) {
		this.wxApiProcess = wxApiProcess;
	}
	
}
